package com.antdesignbackend.backend.common.web;

import com.antdesignbackend.backend.aop.AuthToken;
import com.antdesignbackend.backend.config.WebConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 图片处理
 */
@Controller
@RequestMapping("/image")
public class ImageController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 图片上传
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @PostMapping("/uploadImages")
    @ResponseBody
    @AuthToken
    public Map<String,String> uploadImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8") ;
        long random =System.currentTimeMillis();
        String dateKey =random+"";
        String localPathDir="";
        String newFileName="";
        String code = "500";
        Map<String,String> map = new HashMap<>();
        if(!WebConfig.uploadImage.equals(""))
        {
            localPathDir=WebConfig.uploadImage;
        }
        else
        {
            localPathDir= ResourceUtils.getURL("classpath:").getPath()+"images/";
        }
        File logoSaveFile = new File(localPathDir);
        if(!logoSaveFile.exists()){
            logoSaveFile.mkdirs();
        }
        try {
            if (request instanceof MultipartHttpServletRequest) {
                MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
                Iterator iter = mr.getFileMap().values().iterator();
                if (iter.hasNext()) {
                    MultipartFile file = (MultipartFile) iter.next();
                    String oname = file.getOriginalFilename();
                    String fileTyle=oname.substring(oname.lastIndexOf("."),oname.length());
                    fileTyle=fileTyle.toLowerCase();
                    newFileName=dateKey+fileTyle;
                    String fileName = localPathDir+newFileName;
                    if(fileTyle.equals(".png") || fileTyle.equals(".jpg"))
                    {
                        InputStream inputstream =file.getInputStream();
                        byte[] bytes = new byte[1024];
                        FileOutputStream outstream = new FileOutputStream(fileName);
                        int index;
                        while ((index = inputstream.read(bytes)) != -1) {
                            outstream.write(bytes, 0, index);
                            outstream.flush();
                        }
                        outstream.close();
                        inputstream.close();
                    }
                }
            }
        }catch (Exception e){
            logger.error(e.getMessage());
            map.put("code",code);
            return map;
        }
        if(newFileName!=null && !newFileName.equals(""))
        {
            code = "200";
            map.put("url",newFileName);
            map.put("httpUrl",WebConfig.host+"images/"+newFileName);
        }
        map.put("code",code);
        return map;
    }


    @PostMapping("/upload")
    @ResponseBody
    @AuthToken
    public Map<String,Object> upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String,String> map = uploadImage(request,response);
        Map<String,Object> result = new HashMap<>();
        if(map.containsKey("httpUrl")){
            result.put("errno",0);
            result.put("data",new String[]{map.get("httpUrl")});
        }
        return result;
    }
}
